package com.example.teacherservice.controller;

import com.example.teacherservice.dto.*;
import com.example.teacherservice.entity.Chapter;
import com.example.teacherservice.entity.Course;
import com.example.teacherservice.entity.StuCouProgress;
import com.example.teacherservice.exception.ResourceNotFoundException;
import com.example.teacherservice.service.ChapterService;
import com.example.teacherservice.service.CourseService;
import com.example.teacherservice.service.FileStorageService;
import jakarta.annotation.security.PermitAll;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/spoc/vod/course")
public class CourseController {
    private final CourseService courseService;
    private final ChapterService chapterService;
    private final FileStorageService fileStorageService;

    public CourseController(CourseService courseService, ChapterService chapterService, FileStorageService fileStorageService) {
        this.courseService = courseService;
        this.chapterService = chapterService;
        this.fileStorageService = fileStorageService;
    }

    // 新增获取所有课程接口
    @GetMapping("/listAll")
    public ResponseEntity<List<Course>> getAllCourses() {
        List<Course> allCourses = courseService.getAllCourses();
        return ResponseEntity.ok(allCourses);
    }

    // 其他已有接口...
    @PostMapping("/save")
    public ResponseEntity<Course> saveCourse(@RequestBody Course course) {
        Course savedCourse = courseService.saveCourse(course);
        return ResponseEntity.ok(savedCourse);
    }

    @PostMapping("/update")
    public ResponseEntity<Course> updateCourse(@RequestBody Course course) {
        Course updatedCourse = courseService.updateCourse(course);
        return ResponseEntity.ok(updatedCourse);
    }

    @DeleteMapping("/remove/{id}")
    public ResponseEntity<Void> deleteCourse(@PathVariable Long id) {
        courseService.deleteCourse(id);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/teacherCourseList/{teaId}")
    public ResponseEntity<List<Course>> getTeacherCourseList(@PathVariable Long teaId) {
        List<Course> courses = courseService.getTeacherCourseList(teaId);
        return ResponseEntity.ok(courses);
    }

    @GetMapping("/getInfoByTeacher/{id}")
    public ResponseEntity<Course> getCourseInfo(@PathVariable Long id) {
        Course course = courseService.getCourseInfo(id);
        return ResponseEntity.ok(course);
    }

    @PutMapping("/publishCourse/{id}")
    public ResponseEntity<Course> publishCourse(@PathVariable Long id) {
        Course course = courseService.publishCourse(id);
        return ResponseEntity.ok(course);
    }

    /**
     * 根据教师ID获取所有课程
     * @param teaId 教师ID
     * @return 课程列表
     */
    @GetMapping("/teacher/{teaId}")
    public ResponseEntity<List<Course>> getCoursesByTeacherId(@PathVariable Long teaId) {
        List<Course> courses = courseService.getCoursesByTeacherId(teaId);
        return ResponseEntity.ok(courses);
    }

    /**
     * 创建课程
     * @param createCourseDTO 课程数据(包含teaId)
     * @return 创建的课程
     */
    @PostMapping("/create")
    public ResponseEntity<Course> createCourse(
            @Validated @RequestBody CreateCourseDTO createCourseDTO) {

        Course createdCourse = courseService.createCourseWithChapters(createCourseDTO);
        return ResponseEntity.ok(createdCourse);
    }

    /**
     * 为课程添加章节
     * @param courseId 课程ID
     * @param chapterRequests 章节数据列表
     * @return 新增的章节列表
     */
    @PostMapping("/{courseId}/chapters")
    public ResponseEntity<ApiResponse> addChaptersToCourse(
            @PathVariable Long courseId,
            @RequestPart("data") List<ChapterCreateRequest> chapterRequests,
            @RequestPart(value = "files", required = false) List<MultipartFile> files) throws Exception {

        // 1. 校验文件与请求对应关系
        if (files != null && files.size() != chapterRequests.size()) {
            throw new IllegalArgumentException("文件与章节数量不匹配");
        }

        // 2. 处理每个章节的视频
        List<ChapterDTO> chapters = new ArrayList<>();
        for (int i = 0; i < chapterRequests.size(); i++) {
            ChapterCreateRequest request = chapterRequests.get(i);

            // 如果有上传文件，优先处理文件
            if (files != null && !files.get(i).isEmpty()) {
                String videoUrl = fileStorageService.handleVideoUpload(files.get(i), courseId);
                request.setUrl(videoUrl); // 覆盖原有URL
            }
            // 调用服务保存章节
            chapters.add(chapterService.createChapter(request));
        }

        return ResponseEntity.ok(new ApiResponse(true, "章节添加成功", chapters));
    }


    // 新增批量创建接口
    // 删除CreateCourseWithChaptersDTO，直接使用CreateCourseDTO
    @PostMapping("/create-with-chapters")
    public ResponseEntity<Course> createCourseWithChapters(
            @RequestBody CreateCourseDTO dto) { // 移除@RequestPart，只接受JSON

        // 处理章节视频URL（不处理文件上传）
        if(dto.getChapters() != null) {
            dto.getChapters().forEach(chapter -> {
                if(chapter.getUrl() != null && !chapter.getUrl().isBlank()) {
                    // 可以添加URL验证逻辑
                    if(!isValidUrl(chapter.getUrl())) {
                        throw new IllegalArgumentException("无效的视频URL: " + chapter.getUrl());
                    }
                }
            });
        }

        Course createdCourse = courseService.createCourseWithChapters(dto);
        return ResponseEntity.ok(createdCourse);
    }

    private boolean isValidUrl(String url) {
        // 实现URL验证逻辑
        return url.matches("^(http|https)://.*");
    }


    /**
     * 根据课程ID更新课程信息（仅限名称和简介）
     * @param id 课程ID
     * @param updateDTO 更新数据
     * @return 更新后的课程
     */
    @PatchMapping("/{id}")
    @PermitAll
    @CrossOrigin(origins = "http://localhost:8080") // 强制允许前端域名
    public ResponseEntity<Course> updateCourseInfo(
            @PathVariable Long id,
            @RequestBody CourseUpdateDTO updateDTO) {

        System.out.println("请求到达: "+ updateDTO); // 添加日志
        Course updatedCourse = courseService.updateCourseInfo(id, updateDTO);
        return ResponseEntity.ok(updatedCourse);
    }


    /**
     * 添加课程到班级
     * @param classId 班级ID
     * @param courseId 课程ID
     * @return 操作结果
     */
    @PostMapping("/{classId}/courses/{courseId}")
    public ResponseEntity<?> addCourseToClass(
            @PathVariable Long classId,
            @PathVariable Long courseId) {

        try {
            boolean result = courseService.addCourseToClass(classId, courseId);
            return ResponseEntity.ok().body(Map.of(
                    "success", true,
                    "message", "课程添加成功"
            ));
        } catch (ResourceNotFoundException e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(Map.of(
                            "success", false,
                            "message", e.getMessage()
                    ));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest()
                    .body(Map.of(
                            "success", false,
                            "message", e.getMessage()
                    ));
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                    .body(Map.of(
                            "success", false,
                            "message", "添加课程失败"
                    ));
        }
    }

    /**
     * 批量添加课程到班级
     * @param classId 班级ID
     * @param courseIds 课程ID列表
     * @return 操作结果
     */
    @PostMapping("/{classId}/courses/batch")
    public ResponseEntity<?> batchAddCoursesToClass(
            @PathVariable Long classId,
            @RequestBody List<Long> courseIds) {

        try {
            int successCount = 0;
            List<String> messages = new ArrayList<>();

            for (Long courseId : courseIds) {
                try {
                    courseService.addCourseToClass(classId, courseId);
                    successCount++;
                } catch (Exception e) {
                    messages.add("课程ID " + courseId + ": " + e.getMessage());
                }
            }

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("addedCount", successCount);
            response.put("totalCount", courseIds.size());
            response.put("messages", messages);

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                    .body(Map.of(
                            "success", false,
                            "message", "批量添加课程失败"
                    ));
        }
    }

    /**
     * 从班级移除课程
     * @param classId 班级ID
     * @param courseId 课程ID
     * @return 操作结果
     */
    @DeleteMapping("/{classId}/courses/{courseId}")
    public ResponseEntity<?> removeCourseFromClass(
            @PathVariable Long classId,
            @PathVariable Long courseId) {

        try {
            boolean result = courseService.removeCourseFromClass(classId, courseId);
            return ResponseEntity.ok().body(Map.of(
                    "success", true,
                    "message", "课程移除成功"
            ));
        } catch (ResourceNotFoundException e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(Map.of(
                            "success", false,
                            "message", e.getMessage()
                    ));
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                    .body(Map.of(
                            "success", false,
                            "message", "移除课程失败"
                    ));
        }
    }

    /**
     * 获取所有价格大于0的课程
     * @return 价格大于0的课程列表
     */
    @GetMapping("/paid-courses")
    public ResponseEntity<List<Course>> getPaidCourses() {
        // 获取所有课程
        List<Course> allCourses = courseService.getAllCourses();

        // 过滤出价格大于0的课程
        List<Course> paidCourses = allCourses.stream()
                .filter(course -> course.getCouPrice() > 0)
                .collect(Collectors.toList());

        return ResponseEntity.ok(paidCourses);
    }




}